package com.threeox.commonlibrary.util;

import android.content.Intent;

import com.alibaba.fastjson.JSONObject;
import com.threeox.commonlibrary.CommonApplcation;
import com.threeox.commonlibrary.config.CommonConfig;
import com.threeox.utillibrary.util.EmptyUtils;
import com.threeox.utillibrary.util.IntentUtils;
import com.threeox.utillibrary.util.LogUtils;
import com.threeox.utillibrary.util.res.IdHelper;
import com.threeox.utillibrary.util.res.StringHelper;

import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @ClassName: RegexHelper
 *
 * @Description: TODO(正则工具类)
 *
 * @author 赵屈犇
 *
 * @date 创建时间:2016/12/19 下午9:31
 *
 * @version 1.0
 */
public class RegexHelper {

    private static final String TAG = "RegexHelper";

    /**
     * 替换参数
     *
     * @param data
     *          被替换的参数
     * @param replaceKeys
     *          替换的Key值
     * @param replaceData
     *          替换的结果值
     * @return
     */
    public static void replace(JSONObject data, JSONObject replaceKeys, Object replaceData) {
        replace(data, replaceKeys, replaceData, false);
    }

    /**
     * 替换参数
     *
     * @param data
     *          被替换的参数
     * @param replaceKeys
     *          替换的Key值
     * @param replaceData
     *          替换的结果值
     * @param isReplace
     *          是否属于替换
     * @return
     */
    public static void replace(JSONObject data, JSONObject replaceKeys, Object replaceData, boolean isReplace) {
        // 参数统一不能为空
        if (EmptyUtils.isEmpty(data) || EmptyUtils.isEmpty(replaceKeys) || EmptyUtils.isEmpty(replaceData))
            return;
        for (String key: replaceKeys.keySet()) {
            try {
                String replaceKey = replaceKeys.getString(key);
                boolean flag = true;
                if (replaceData instanceof JSONObject) {
                    flag = ((JSONObject) replaceData).containsKey(replaceKey);
                } else if (replaceData instanceof Intent) {
                    flag = ((Intent) replaceData).getExtras().containsKey(replaceKey);
                    isReplace = true;
                } else {
                    Object result = ValueUtils.getObjValue(replaceData, replaceKey);
                    if (result != null) {
                        JSONUtils.putJSONValue(data, key, result);
                    } else {
                        if (!isReplace) {
                            removeReplaceJSON(data, key);
                        }
                    }
                    continue;
                }
                if (flag) {
                    Object result = ValueUtils.getObjValue(replaceData, replaceKey);
                    JSONUtils.putJSONValue(data, key, result);
                } else {
                    if (!isReplace) {
                        removeReplaceJSON(data, key);
                    }
                }
            } catch (Exception e) {
                LogUtils.e(TAG, e.getMessage());
            }
        }
    }

    /**
     * 删除不存储的数据
     *
     * @param data
     * @param key
     */
    public static void removeReplaceJSON(JSONObject data, String key) {
        Object value = JSONUtils.getJSONValue(data, key);
        if (EmptyUtils.isNotEmpty(value)) {
            Pattern patten = Pattern.compile(CommonConstant.RegularExp.EL_REG);// 正则判断是否属于${}
            Matcher matcher = patten.matcher(String.valueOf(value));
            while (matcher.find()) {
                JSONUtils.removeJSONValue(data, key);
            }
        }
    }


    /**
     * 替换${}
     *
     * @param params
     * @param intent
     * @return
    public static JSONObject replace$(JSONObject params, Intent intent) {
        if (intent == null) {
            return params;
        }
        if (params != null) {
            // 将所有的${}表达式用intent传入的值替代
            Set<String> set = params.keySet();
            for (String key : set) {
                Object val = params.get(key);
                if (val instanceof String) {
                    val = replace$(val.toString(), intent);
                    // val = replaceExp(val);
                    params.put(key, val);
                } else if (val instanceof JSONObject) {
                    JSONObject data = replace$((JSONObject) val, intent);
                    if (data != null)
                        params.putAll(data);
                }
            }
        }
        return params;
    } */

    /**
     * 替换${}
     *
     * @param param
     * @param intent
     * @return
     */
    public static String replace$(String param, Intent intent) {
        // 将所有的${}表达式用intent传入的值替代
        if (EmptyUtils.isNotEmpty(param)) {
            Pattern patten = Pattern.compile(CommonConstant.RegularExp.EL_REG);// 正则判断是否属于${}
            Matcher matcher = patten.matcher(param);
            while (matcher.find()) {
                String group = matcher.group(1);
                Object data = IntentUtils.get(intent, group);
                if (data != null) {
                    if (("${" + group + "}").equals(param)) {
                        param = data.toString();
                    } else {
                        param = ((String) param).replace("${" + group + "}", String.valueOf(data));
                    }
                } else {
                    LogUtils.e("替换${}", "intent没有传入" + group + "参数,请传入!");
                }
            }
        }
        return param;
    }

    /**
     * 替换字符串中的${}
     *
     * @param param
     * @param params
     * @return
     *
     */
    public static String replace$(String param, JSONObject params) {
        if (EmptyUtils.isNotEmpty(param) && EmptyUtils.isNotEmpty(params)) {
            String result = new String(param);
            Pattern patten = Pattern.compile(CommonConstant.RegularExp.EL_REG);// 正则判断是否属于${}
            Matcher matcher = patten.matcher(result);
            while (matcher.find()) {
                String group = matcher.group(1);
                Object data = JSONUtils.getJSONValue(params, group);
                if (data != null) {
                    if (("${" + group + "}").equals(result)) {
                        result = data.toString();
                    } else {
                        result = result.replace("${" + group + "}", String.valueOf(data));
                    }
                } else {
                    LogUtils.e("替换${}", "intent没有传入" + group + "参数,请传入!");
                }
            }
            return result;
        }
        return param;
    }

    /**
     * 替换${}
     *
     * @param params
     * @param dataJson
     * @return
     *
     */
    public static JSONObject replace$(JSONObject params, JSONObject dataJson) {
        if (dataJson == null) {
            return params;
        }
        if (params != null) {
            // 将所有的${}表达式用intent传入的值替代
            Set<String> set = params.keySet();
            for (String key : set) {
                Object val = params.get(key);
                if (val instanceof String) {
                    Pattern patten = Pattern.compile(CommonConstant.RegularExp.EL_REG);// 正则判断是否属于${}
                    Matcher matcher = patten.matcher(val.toString());
                    while (matcher.find()) {
                        String group = matcher.group(1);
                        Object data = dataJson.get(group);
                        if (data != null) {
                            if (("${" + group + "}").equals(val)) {
                                val = data;
                            } else {
                                val = ((String) val).replace("${" + group + "}", String.valueOf(data));
                            }
                        } else {
                            LogUtils.e("替换${}", "intent没有传入" + group + "参数,请传入!");
                        }
                    }
                    params.put(key, val);
                } else if (val instanceof JSONObject) {
                    replace$((JSONObject) val, dataJson);
                    //if (data != null)
                    // params.putAll(data);
                }
            }
        }
        return params;
    }


    /**
     * 替换数据
     *
     * @param params
     * @param datas
     * @return
    public static JSONObject replaceData(JSONObject params, JSONObject datas) {
        if (EmptyUtils.isEmpty(params)) {
            return params;
        }
        if (EmptyUtils.isNotEmpty(datas)) {
            Set<String> data = datas.keySet();
            for (String key: data) {
                try {
                    Object result = JSONUtils.getJSONValue(datas, key);
                    JSONUtils.putJSONData(params, key, result);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return params;
    }*/


    /**
     * 替换存放在系统资源的不可变资源
     *
     * @param params
     * @return
     */
    public static JSONObject replaceSys(JSONObject params) {
        if (params != null) {
            /** 将所有的${}表达式用intent传入的值替代 */
            Set<String> set = params.keySet();
            for (String key : set) {
                Object val = params.get(key);
                if (val instanceof String) {
                    val = replaceSys(val);
                }
                params.put(key, val);
            }
        }
        return params;
    }

    /**
     * 替换存放在系统资源的不可变资源
     *
     * @param val
     * @return
     */
    public static Object replaceSys(Object val) {
        try {
            Pattern rawPatten = Pattern.compile(CommonConstant.RegularExp.RAW_REG);// 正则判断是否属于RAW{}
            Matcher rawMatcher = rawPatten.matcher(val.toString());
            if (rawMatcher.find()) {
                String group = rawMatcher.group(1);
                val = IdHelper.newInstance(CommonApplcation.getInstance()).getIdByName(group, IdHelper.ResType.raw);
            }
            Pattern strPatten = Pattern.compile(CommonConstant.RegularExp.STR_REG);// 正则判断是否属于STR{}
            Matcher strMatcher = strPatten.matcher(val.toString());
            if (strMatcher.find()) {
                String group = strMatcher.group(1);
                val = StringHelper.newInstance(CommonApplcation.getInstance()).getStringText(group);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return val;
    }

    /**
     * 得到可以替换的主键集合
     *
     * @param data
     * @return
     */
    public static JSONObject getReplaceKeys(JSONObject data) {
        if (EmptyUtils.isNotEmpty(data)) {
            JSONObject keys = new JSONObject();
            for (String key: data.keySet()) {
                Object value = data.get(key);
                JSONObject result = getReplaceKey(key, value);
                if (EmptyUtils.isNotEmpty(result)) {
                    keys.putAll(result);
                }
            }
            return keys;
        }
        return null;
    }

    /**
     *
     * @param key
     * @param value
     * @return
     */
    private static JSONObject getReplaceKey(String key, Object value) {
        try {
            JSONObject result = new JSONObject();
            if (value instanceof JSONObject) {
                JSONObject data = (JSONObject) value;
                JSONObject results = getReplaceKeys(data);
                if (EmptyUtils.isNotEmpty(results)) {
                    for (String resultKey: results.keySet()) {
                        result.put(key + "." + resultKey, results.get(resultKey));
                    }
                }
            } else {
                Pattern patten = Pattern.compile(CommonConstant.RegularExp.EL_REG);// 正则判断是否属于${}
                Matcher matcher = patten.matcher(String.valueOf(value));
                while (matcher.find()) {
                    String group = matcher.group(1);
                    result.put(key, group);
                }
            }
            return result;
        } catch (Exception e) {
            LogUtils.e(TAG, "getReplaceKey:" + e.getMessage());
        }
        return null;
    }


    /**
     * 根据rawName 替换JSON文件
     *
     * @param rawName
     * @param params
     */
    public static void replaceJSONByRawName(String rawName, JSONObject params) {
        try {
            JSONObject datas = CommonConfig.getInstance().getJSONMessage(rawName);
            if (EmptyUtils.isNotEmpty(datas)) {
                if (params == null) {
                    params = new JSONObject();
                }
                Set<String> set = datas.keySet();
                for (String key: set) {
                    params.put(key, datas.get(key));
                }
            }
        } catch (Exception e) {
            LogUtils.e(TAG, "replaceJSONByRawName:" + e.getMessage());
        }
    }

}
